import React, { useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom';
import store from '../../redux/store'
import { Layout, Menu } from 'antd'
import {
  AppstoreOutlined
} from '@ant-design/icons';
import style from './menu.module.css'
import { _getMenuList } from '../../api/menu';

const { Sider } = Layout
const { SubMenu } = Menu;

const SideMenu = (props) => {
  useEffect(() => {
    _getMenuList().then(res => {
      setMenuList(res)
    })
  }, [])
  const [collapsed] = useState(false)
  const [menuList, setMenuList] = useState([])
  if (!store.getState().userInfo) {
    props.history.replace('/login')
    return
  }
  const { role: { rights } } = store.getState().userInfo[0]


  const gotoPage = (item) => {
    props.history.push(item.key)
  }
  const check = (item) => {
    return item.pagepermisson === 1 && rights.includes(item.key)
  }
  const renderMenu = (menuInfo) => {
    return menuInfo.map((item) => {
      if (item.children?.length > 0 && check(item)) {
        return <SubMenu key={item.key} icon={<AppstoreOutlined />} title={item.title}>
          {renderMenu(item.children)}
        </SubMenu>
      }
      return check(item) && <Menu.Item key={item.key} onClick={() => { gotoPage(item) }} icon={<AppstoreOutlined />} >{item.title}</Menu.Item>
    })
  }
  const selectKeys = [props.location.pathname]
  const openKeys = ["/" + props.location.pathname.split("/")[1]]
  return (
    <Sider trigger={null} collapsible collapsed={collapsed} >
      <div className={style.menuBox}>
        <div className={style.logo}><AppstoreOutlined />后台管理系统</div>
        <div className={style.menuItem}>
          <Menu theme="dark" mode="inline" selectedKeys={selectKeys} defaultOpenKeys={openKeys}>
            {renderMenu(menuList)}
          </Menu>
        </div>
      </div>
    </Sider>
  )
}
export default withRouter(SideMenu)